<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
          <el-form-item label="物料编码" prop="itemCode">
            <el-input
                v-model="queryParams.itemCode"
                placeholder="请输入物料编码"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物料名称" prop="itemName">
            <el-input
                v-model="queryParams.itemName"
                placeholder="请输入物料名称"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
<!--          <el-form-item label="剩余月数" prop="daysRemaining">
            <el-input
                v-model="queryParams.daysRemaining"
                placeholder="请输入剩余月数"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>-->
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input
                v-model="queryParams.warehouseName"
                placeholder="请输入仓库名称"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="库区名称" prop="locationName">
            <el-input
                v-model="queryParams.locationName"
                placeholder="请输入库区名称"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="库位名称" prop="areaName">
            <el-input
                v-model="queryParams.areaName"
                placeholder="请输入库位名称"
                clearable
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
    <el-table v-loading="loading" :data="stockwarnList" @selection-change="handleSelectionChange" border>
      <el-table-column label="物料编码" align="center" prop="itemCode"/>
      <el-table-column label="物料名称" align="center" prop="itemName"/>
      <el-table-column label="规格型号" align="center" prop="specification"/>
      <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
      <el-table-column label="批次" align="center" prop="batchCode"/>

      <el-table-column label="仓库" align="center" prop="warehouseName"/>
      <el-table-column label="库区" align="center" prop="locationName"/>
      <el-table-column label="库位" align="center" prop="areaName"/>
      <el-table-column label="当前库存数量" align="center" prop="quantityOnhand"/>
      <el-table-column label="生产日期" align="center" prop="manufactureDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期" align="center" prop="qualityGuaranteePeriod"/>

      <el-table-column label="有效期日期" align="center" prop="expireDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px" align="center" fixed="right">
        <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-hasPermi="['wm:delayrecord:add']"
                @click="handleUpdate(scope.row)"
            >延期</el-button>

            <el-button
                size="mini"
                type="text"
                icon="el-icon-tickets"
                v-hasPermi="['wm:delayrecord:list']"
                @click="handleView(scope.row)"
            >延期记录</el-button>



        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
        <el-row>
          <el-col :span="8">
            <el-form-item label="物料编码" prop="itemCode" >
              <el-input v-model="form.itemCode" placeholder="请选择入库物料" disabled="disabled">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" disabled="disabled" placeholder="请选择入库物料"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" disabled="disabled" placeholder="请输入单位"  />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" disabled="disabled" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="接收仓库" prop="warehouseId" >
              <el-cascader v-model="warehouseInfo"  :disabled="true"
                           :options="warehouseOptions"
                           :props="warehouseProps"
                           style="width:100%"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <!--            要求可以手动填写  readonly="readonly"-->
              <el-input v-model="form.batchCode"  placeholder="请输入批次号" disabled="disabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产日期" prop="manufactureDate" >
              <el-date-picker clearable disabled="disabled"
                              v-model="form.manufactureDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="生产日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质保期" prop="qualityGuaranteePeriod">
              <el-input v-model="form.qualityGuaranteePeriod"  placeholder="" disabled="disabled"/>
            </el-form-item>
          </el-col>
              <!-- 显示有效期  保存到延期-->
          <el-col :span="8">
            <el-form-item label="有效日期" prop="delayDate">
              <el-date-picker clearable
                              v-model="form.delayDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :picker-options="expireDateOptions"
                              placeholder="有效日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Delaydtails ref="deDetail" :title="title" v-if="devisible" @refreshDataList="getList"></Delaydtails>

  </div>
</template>

<script>
import {getWmstock, getValidityList, getInfoFor} from "@/api/mes/wm/wmstock";
import {getTreeList} from "@/api/mes/wm/warehouse";
import {addDelayrecord, updateDelayrecord} from "@/api/mes/wm/delayrecord";
import Delaydtails from "./delaydtails.vue"


export default {
  name: "Validitytockwarn",
  components: {Delaydtails},
  data() {
    return {
      // 新增数据项
      originalExpireDate: null,
      expireDateOptions: {
        disabledDate: (time) => {
          if (this.originalExpireDate) {
            return time.getTime() < new Date(this.originalExpireDate).getTime();
          }
          return false;
          }
        },
      devisible:false,
      warehouseCode: 'XBK_VIRTUAL', //线边库
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存预警表格数据
      stockwarnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: null, itemName: null,
        daysRemaining:null
      },
      // 表单参数
      form: {},
      rules: {
        itemCode: [
          {required: true, message: "物料不能为空", trigger: "blur"}
        ],
        delayDate: [
          { required: true, message: '有效日期不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (new Date(value) < new Date(this.originalExpireDate)) {
                callback(new Error('延期日期不能早于原有效日期'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseList()
  },
  methods: {

    /** 查询库存预警列表 */
    getList() {
      this.loading = true;
      getValidityList(this.queryParams).then(response => {
        this.stockwarnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    handleView(row){
      this.title="延期记录"
      this.devisible=true

      this.$nextTick(() => {
        this.$refs.deDetail.init(row.materialStockId)
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        batchCode: null,
        quantityOnhand: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        manufactureDate: null,
        expireDate: null,
        delayDate:null,
        qualityGuaranteePeriod: null
      };
      this.resetForm("form");
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
          ;
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存预警";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.materialStockId
      getInfoFor(id).then(response => {
        this.form = response.data;
        this.originalExpireDate = response.data.expireDate;
        this.$nextTick(() => {
          this.warehouseInfo = [
            response.data.warehouseId,
            response.data.locationId,
            response.data.areaId
          ];
          this.$set(this.form, "delayDate",response.data.expireDate);
          this.$forceUpdate()
        });
        this.open = true;
        this.title = "修改库存有效期";
      });
    },
    /** 提交按钮 */
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDelayrecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDelayrecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存预警编号为"' + ids + '"的数据项？').then(function () {
        return delStockwarn(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/wm/stockwarn/export', {
        ...this.queryParams
      }, `stockwarn_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
